package org.smr.dev;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;

public class AbstractCodeGenerator {

	private String templateFileName;

	private Map<String, Object> velocityVariables;

	private String output2FilePathAndName;

	public void generate() {
		
		VelocityEngine ve = new VelocityEngine();
		Properties p = new Properties();
		p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		ve.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		ve.init(p);
		
		Template actionTpt = ve.getTemplate(templateFileName);
		VelocityContext ctx = new VelocityContext();

		for (Map.Entry<String, Object> entry : velocityVariables.entrySet()) {
			ctx.put(entry.getKey(), entry.getValue());
		}

		String rootPath = Test.class.getClassLoader().getResource("").getFile();
		System.out.println(rootPath);
		merge(actionTpt, ctx, output2FilePathAndName);
	}

	private void merge(Template template, VelocityContext ctx, String path) {
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(path);
			template.merge(ctx, writer);
			writer.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			writer.close();
		}
	}

	public String getTemplateFileName() {
		return templateFileName;
	}

	public void setTemplateFileName(String templateFileName) {
		this.templateFileName = templateFileName;
	}

	public Map<String, Object> getVelocityVariables() {
		return velocityVariables;
	}

	public void setVelocityVariables(Map<String, Object> velocityVariables) {
		this.velocityVariables = velocityVariables;
	}

	public String getOutput2FilePathAndName() {
		return output2FilePathAndName;
	}

	public void setOutput2FilePathAndName(String output2FilePathAndName) {
		this.output2FilePathAndName = output2FilePathAndName;
	}

	public AbstractCodeGenerator(String templateFileName, Map<String, Object> velocityVariables,
			String output2FilePathAndName) {
		super();
		this.templateFileName = templateFileName;
		this.velocityVariables = velocityVariables;
		this.output2FilePathAndName = output2FilePathAndName;
	}

}
